﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

using Microsoft.Phone.Controls;

namespace YourLastOptionsDialog.Views
{
    /// <summary>
    /// A color editor using the <c>Coding4Fun</c> color slider.
    /// </summary>
    public partial class ColorEditor : UserControl
    {
        private Pivot _pivot;

        private Pivot PivotControl
        {
            get
            {
                if (_pivot == null)
                {
                    FrameworkElement parent = this;
                    while (parent != null && parent.GetType() != typeof(Pivot))
                    {
                        parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;
                    }

                    _pivot = parent as Pivot;
                }

                return _pivot;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ColorEditor"/> class.
        /// </summary>
        public ColorEditor()
        {
            // Required to initialize variables
            InitializeComponent();

            Loaded += ColorEditor_Loaded;
            Unloaded += ColorEditor_Unloaded;
        }

        private void ColorEditor_Loaded(object sender, RoutedEventArgs e)
        {
            // disable pivot sliding if interacting with the color slider
            ColorSlider.ManipulationStarted += ColorSlider_ManipulationStarted;
            Touch.FrameReported += Touch_FrameReported;
        }

        private void ColorEditor_Unloaded(object sender, RoutedEventArgs e)
        {
            // remove event handlers
            ColorSlider.ManipulationStarted -= ColorSlider_ManipulationStarted;
            Touch.FrameReported -= Touch_FrameReported;
        }

        private void Touch_FrameReported(object sender, TouchFrameEventArgs e)
        {
            if (e.GetPrimaryTouchPoint(ColorSlider).Action == TouchAction.Up)
            {
                if (PivotControl != null)
                {
                    PivotControl.IsHitTestVisible = true;
                }
            }
        }

        private void ColorSlider_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            if (PivotControl != null)
            {
                PivotControl.IsHitTestVisible = false;
            }
        }
    }
}